package com.tbynet.jwp.repository.impl;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.tbynet.jwp.framework.aop.Aop;
import com.tbynet.jwp.framework.core._JwpServiceProvider;
import com.tbynet.jwp.framework.kit.DateKit;
import com.tbynet.jwp.model.Posts;
import com.tbynet.jwp.repository.spi.PostScheduleService;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

@Aop(PostScheduleService.class)
public class PostScheduleServiceImpl extends _JwpServiceProvider<Posts> implements PostScheduleService {

    @Override
    protected String buildSearchWhereSql(String keyword, List<Object> params) {
        return "";
    }

    @Override
    public boolean schedulePublish(Object postId, Date publishTime) {
        return Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                Posts post = getDao().findById(postId);
                if (post == null) {
                    return false;
                }

                // 设置文章状态为future（定时发布）
                post.setPostStatus(Posts.POST_STATUS_FUTURE);
                post.setPostDate(publishTime);
                post.setPostDateGmt(publishTime);

                // 更新文章
                return post.update();
            }
        });
    }

    @Override
    public boolean cancelSchedule(Object postId) {
        return Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                Posts post = getDao().findById(postId);
                if (post == null) {
                    return false;
                }

                // 取消定时发布，状态改为草稿
                post.setPostStatus(Posts.POST_STATUS_DRAFT);
                post.setPostDate(new Date());
                post.setPostDateGmt(new Date());

                return post.update();
            }
        });
    }

    @Override
    public List<Posts> getScheduledPosts() {
        String sql = "SELECT * FROM wp_posts WHERE post_type = 'post' " +
                "AND post_status = 'future' AND post_date > ? " +
                "ORDER BY post_date ASC";

        return getDao().find(sql, new Date());
    }

    @Override
    public void executeScheduledPublish() {
        List<Posts> scheduledPosts = getScheduledPosts();
        Date now = new Date();

        for (Posts post : scheduledPosts) {
            // 检查是否到达发布时间
            if (post.getPostDate().before(now) || post.getPostDate().equals(now)) {
                // 发布文章
                post.setPostStatus(Posts.POST_STATUS_PUBLISH);
                post.setPostDate(now);
                post.setPostDateGmt(now);
                post.update();

                // 记录发布日志
                logPublish(post.getID());
            }
        }
    }

    @Override
    public boolean isScheduled(Object postId) {
        Posts post = getDao().findById(postId);
        return post != null && Posts.POST_STATUS_FUTURE.equals(post.getPostStatus());
    }

    @Override
    public Date getScheduledTime(Object postId) {
        Posts post = getDao().findById(postId);
        if (post != null && Posts.POST_STATUS_FUTURE.equals(post.getPostStatus())) {
            return post.getPostDate();
        }
        return null;
    }

    @Override
    public boolean batchSchedule(List<Object> postIds, Date publishTime) {
        return Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                for (Object postId : postIds) {
                    if (!schedulePublish(postId, publishTime)) {
                        return false;
                    }
                }
                return true;
            }
        });
    }

    /**
     * 记录发布日志
     */
    private void logPublish(Object postId) {
        String sql = "INSERT INTO wp_postmeta (post_id, meta_key, meta_value) VALUES (?, '_scheduled_publish_log', ?)";
        String logValue = "Published at: " + DateKit.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        Db.update(sql, postId, logValue);
    }

    /**
     * 获取发布历史
     */
    public List<Record> getPublishHistory(Object postId) {
        String sql = "SELECT meta_value FROM wp_postmeta WHERE post_id = ? AND meta_key = '_scheduled_publish_log' ORDER BY meta_id DESC";
        return Db.find(sql, postId);
    }
}
